﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;

namespace BBYScripts
{
    public class ItemChecker : MonoBehaviour
    {
        private static BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.NonPublic |
                                                   BindingFlags.Instance | BindingFlags.Public;

        private void OnParticleCollision(GameObject other)
        {
            PrintObjectMembers(other);
        }

        private void PrintObjectMembers(GameObject obj)
        {
            if (obj == null)
            {
                return;
            }
            Debug.LogError("name:" + obj.name + ";layer:" + obj.layer + ";obj:" + obj);
            Debug.LogError($"对象类型: {obj.GetType().Name}");

            // 打印属性
            var properties = obj.GetType().GetProperties(bindingFlags);
            var memberNames = properties.Select(property =>
            {
                var propertyName = property.GetType() + " " + property.Name;
                var val = "fail";
                try
                {
                    var valObj = property.GetValue(obj);
                    if (valObj != null)
                    {
                        val = valObj.ToString();
                    }
                }
                catch (Exception e)
                {
                }

                return propertyName + " = " + val;
            }).ToList();
            PrintList("属性", memberNames);

            // 打印方法
            var methods = obj.GetType().GetMethods(bindingFlags);
            var methodNames = methods.Select(method => method.ReturnType + " " + method.Name + GetParams(method))
                .ToList();
            PrintList("方法", methodNames);
        }

        private static void PrintList(string name, List<string> list)
        {
            Debug.LogError("+++++++++++++++++++" + name + "+++++++++++++++++++");
            Debug.LogError(string.Join("\n", list));
        }

        private static string GetParams(MethodInfo method)
        {
            var parameterInfos = method.GetParameters();
            var list = parameterInfos.Select(p => p.GetType() + " " + p.Name).ToList();
            return "(" + string.Join(", ", list) + ");";
        }
    }
}